#include <QMessageBox>
#include <QtPlugin>

#include "hex.h"

QString HexCodec::escape(const char &ch)
{
	if ( (ch == 13) || (ch == 10) ) return QString("<br/>");
	if ( ch < 32 ) return QString(".");
	if ( ch == '<' ) return QString("&lt;");
	if ( ch == '>' ) return QString("&gt;");
	if ( ch == '&' ) return QString("&amp;");
	if ( ch == '\"' ) return QString("&quot;");
	if ( ch == '\'' ) return QString("&apos;");

	return QString(ch);
}

HexCodec::HexCodec()
{
}

HexCodec::~HexCodec()
{
}

// decode data
QString HexCodec::decode(const QByteArray& ba, const bool toServer)
{
	const char *data = ba.constData();
	const int SIZE = ba.size();
	const int STR_LENGTH = 16;
	const int LINES = SIZE / STR_LENGTH + ( ( SIZE % STR_LENGTH == 0 ) ? 1 : 0 );

	QString add, ret="<table>";
	int i, j;
	int DataPointer;
	
	for(i=0; i < LINES; ++i)
	{
		add = "<tr>";
		
		for(j=0; j<STR_LENGTH; ++j)
		{
			DataPointer = i*STR_LENGTH +j;
		
			if (SIZE < DataPointer)
			{
				add += "<td>"
					+ QString("%1").arg((unsigned char)data[DataPointer], 2, 16, QChar('0')).toUpper()
					+ "</td>";
			}
			else
			{
				add += "<td>  </td>";
			}
		}
	
		add += " <td> </td> ";
		for(j=0; j<STR_LENGTH; ++j)
			add += "<td>" + escape(data[i*STR_LENGTH +j]) + "</td>";
		add += "</tr>";
	
	}
	ret += "</table>";
	
	if (toServer) ret = "<font color=red>"   + ret + "</font>"; // client->server  - red color
	else          ret = "<font color=green>" + ret + "</font>"; // server->client  - green color
	
	return ret;
}

// encode data for send
QByteArray HexCodec::encode(const QString& str, const bool toServer)
{
	//TODO
	return QByteArray();
}

// returns codec short name for menu
QString HexCodec::codecName()
{
	return QString("hex");
}

// return codec description
QString HexCodec::codecDesc()
{
	return QString("shows data in hex");
}

TParams HexCodec::params()
{
	// no params
	TParams t;
	return t;
}

void HexCodec::setParams(TParams&)
{
	// ignore
}

void HexCodec::showParamsDialog()
{
	QString text = "This is a <b>hex</b> codec.";
	QMessageBox::about(0, "hex", text);
}

// Change for your file name (TARGET in .pro) and class name
Q_EXPORT_PLUGIN2(hex, HexCodec);

// kate: space-indent off; tab-indents on; indent-width 4; indent-mode cstyle;
